package com.osell.selection.ui.main;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.transition.TransitionManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.osell.selection.data.network.RestAPI;
import com.osell.selection.data.network.entity.SilkHomeInfo;
import com.osell.selection.ui.base.BaseFragment;
import com.osell.selection.ui.common.WebViewActivity;
import com.osell.selection.util.DimenUtils;
import com.osell.selection.util.Spans;
import com.osell.selection.widget.SilkProduceView;
import com.robinhood.ticker.TickerUtils;
import com.robinhood.ticker.TickerView;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;

public class SilkFragment extends BaseFragment implements View.OnClickListener {

    @BindView(R.id.srl_silk)
    SwipeRefreshLayout srl_silk;
    @BindView(R.id.ll_total_silk_info)
    LinearLayout ll_total_silk_info;
    @BindView(R.id.tv_total_silk_amount)
    TickerView tv_total_silk_amount;
    @BindView(R.id.tv_total_silk_power)
    TextView tv_total_silk_power;
    @BindView(R.id.tv_go_to_increase_power)
    TextView tv_go_to_increase_power;
    @BindView(R.id.spv_silk)
    SilkProduceView spv_silk;
    @BindView(R.id.ll_latest_record)
    LinearLayout ll_latest_record;
    @BindView(R.id.tv_in_production)
    TextView tv_in_production;
    @BindView(R.id.tv_more_records)
    TextView tv_more_records;

    private Unbinder mUnBinder;

    private SoundPool mSoundPool;
    private int mSoundID;
    private double mTotalSilkAmount;

    private DecimalFormat mDecimalFormat = new DecimalFormat("0.0000");

    private CompositeDisposable compositeDisposable;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_silk, container, false);
        mUnBinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        compositeDisposable = new CompositeDisposable();
        mSoundPool = new SoundPool(1,// 同时播放的音效
                AudioManager.STREAM_MUSIC, 0);
        mSoundID = mSoundPool.load(getContext(), R.raw.silk_recieve_coin, 1);

        srl_silk.setColorSchemeResources(R.color.colorPrimary);
        srl_silk.setOnRefreshListener(this::refresh);
        tv_total_silk_amount.setCharacterLists(TickerUtils.provideNumberList());
        tv_total_silk_amount.setAnimationDuration(1500);
        tv_go_to_increase_power.setOnClickListener(this);
        tv_more_records.setOnClickListener(this);

        Drawable drawable = ContextCompat.getDrawable(view.getContext(), R.drawable.ic_silk_produced);
        if (drawable != null) {
            drawable.setBounds(0,
                    0,
                    (int) DimenUtils.dipToPixels((int) (49 * 1.5), view.getContext()),
                    (int) DimenUtils.dipToPixels((int) (53 * 1.5), view.getContext()));
        }
        tv_in_production.setCompoundDrawables(null, drawable, null, null);

        animateTheInProduction();
        refresh();
    }

    @Override
    public void onDestroyView() {
        if (tv_in_production.getTag() != null) {
            ((ObjectAnimator) tv_in_production.getTag()).cancel();
        }
        for (int i = 0; i < spv_silk.getChildCount(); i++) {
            View view = spv_silk.getChildAt(i);
            if (((SilkProduceView.LayoutParams) view.getLayoutParams()).layoutMode == SilkProduceView.LayoutParams.RANDOM) {
                if (view.getTag(R.id.spv_silk) != null) {
                    ((AnimatorSet) view.getTag(R.id.spv_silk)).cancel();
                }
            }
        }
        super.onDestroyView();
        mSoundPool.release();
        mUnBinder.unbind();
        compositeDisposable.dispose();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_go_to_increase_power:
                startActivity(new Intent(v.getContext(), WebViewActivity.class)
                        .putExtra("url", "http://m.sk.osell.com/power-index"));
                break;
            case R.id.tv_more_records:
                startActivity(new Intent(v.getContext(), WebViewActivity.class)
                        .putExtra("url", "http://m.sk.osell.com/member-pdex?opnew=1"));
                break;
            default:
                break;
        }
    }

    private void refresh() {
        setupContent();
    }

    private void setupContent() {
        compositeDisposable.add(RestAPI.getInstance().oSellService()
                .getSilkHomeInfo(mUserInfoSp.getString("user_id", ""),
                        mUserInfoSp.getString("user_key", ""))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(listResponseData -> {
                    srl_silk.setRefreshing(false);
                    if (TextUtils.equals("000000", listResponseData.code)) {
                        mTotalSilkAmount = listResponseData.data.balance;
                        tv_total_silk_amount.setText(getString(R.string.silk_amount, mDecimalFormat.format(mTotalSilkAmount)));
                        tv_total_silk_power.setText(getString(R.string.present_power_value, String.valueOf(listResponseData.data.totalPower)));

                        if (listResponseData.data != null
                                && listResponseData.data.receivedRecords != null
                                && !listResponseData.data.receivedRecords.isEmpty()) {
                            TransitionManager.beginDelayedTransition(ll_latest_record);

                            ll_latest_record.removeAllViews();
                            LayoutInflater layoutInflater = LayoutInflater.from(ll_latest_record.getContext());
                            int i = 0;
                            for (SilkHomeInfo.SilkProduceRecord item : listResponseData.data.receivedRecords) {
                                if (i == 10) {
                                    break;
                                }
                                View view = layoutInflater.inflate(R.layout.silk_produce_record_item, ll_latest_record, false);
                                TextView tv_amount = view.findViewById(R.id.tv_amount);
                                TextView tv_time = view.findViewById(R.id.tv_time);
                                tv_amount.setText(new Spans()
                                        .append(mDecimalFormat.format(item.amount),
                                                new ForegroundColorSpan(0xfffe6400),
                                                new StyleSpan(Typeface.BOLD))
                                        .append(" ")
                                        .append(getString(R.string.silk)));
                                tv_time.setText(item.createtime);
                                ll_latest_record.addView(view);
                                i++;
                            }
                        }

                        if (listResponseData.data != null
                                && listResponseData.data.unReceivedRecords != null
                                && !listResponseData.data.unReceivedRecords.isEmpty()) {
                            List<View> randomViews = new ArrayList<>();
                            int count = spv_silk.getChildCount();
                            for (int i = 0; i < count; i++) {
                                View view = spv_silk.getChildAt(i);
                                if (((SilkProduceView.LayoutParams) view.getLayoutParams()).layoutMode == SilkProduceView.LayoutParams.RANDOM) {
                                    randomViews.add(view);
                                }
                            }
                            for (View view : randomViews) {
                                if (view.getTag(R.id.spv_silk) != null) {
                                    ((AnimatorSet) view.getTag(R.id.spv_silk)).cancel();
                                }
                                spv_silk.removeView(view);
                            }
                            int i = 0;
                            for (SilkHomeInfo.SilkProduceRecord item : listResponseData.data.unReceivedRecords) {
                                if (i >= 5) {
                                    break;
                                }
                                spv_silk.addView(buildSilk(item),
                                        new SilkProduceView.LayoutParams(
                                                ViewGroup.LayoutParams.WRAP_CONTENT,
                                                ViewGroup.LayoutParams.WRAP_CONTENT,
                                                Gravity.START | Gravity.TOP,
                                                SilkProduceView.LayoutParams.RANDOM));
                                i++;
                            }
                            animateTheSilk();
                        }
                    } else {
                        Toast.makeText(MyApplication.getInstance(), listResponseData.message, Toast.LENGTH_SHORT).show();
                    }
                }, throwable -> srl_silk.setRefreshing(false)));
    }

    private TextView buildSilk(SilkHomeInfo.SilkProduceRecord data) {
        TextView textView = new TextView(getContext());
        textView.setGravity(Gravity.CENTER);
        textView.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.ic_silk_produced, 0, 0);
        textView.setTextColor(0xffffffff);
        textView.setTextSize(10);
        textView.setText(mDecimalFormat.format(data.amount));

        ObjectAnimator animatorAlpha = ObjectAnimator.ofFloat(textView, View.ALPHA, 1f, 0.2f);
        animatorAlpha.setRepeatMode(ValueAnimator.REVERSE);
        animatorAlpha.setRepeatCount(ValueAnimator.INFINITE);
        ObjectAnimator animatorScaleX = ObjectAnimator.ofFloat(textView, View.SCALE_X, 1f, 0.9f);
        animatorScaleX.setRepeatMode(ValueAnimator.REVERSE);
        animatorScaleX.setRepeatCount(ValueAnimator.INFINITE);
        ObjectAnimator animatorScaleY = ObjectAnimator.ofFloat(textView, View.SCALE_Y, 1f, 0.9f);
        animatorScaleY.setRepeatMode(ValueAnimator.REVERSE);
        animatorScaleY.setRepeatCount(ValueAnimator.INFINITE);
        AnimatorSet animatorSet = new AnimatorSet().setDuration(1000);
        animatorSet.setStartDelay(new Random().nextInt(5000));
        animatorSet.playTogether(animatorAlpha, animatorScaleX, animatorScaleY);

        textView.setTag(data);
        textView.setTag(R.id.spv_silk, animatorSet);

        textView.setOnClickListener(v -> {
            ((AnimatorSet) v.getTag(R.id.spv_silk)).cancel();
            v.animate()
                    .x(ll_total_silk_info.getX())
                    .y(ll_total_silk_info.getY())
                    .setListener(new AnimatorListenerAdapter() {
                        @Override
                        public void onAnimationEnd(Animator animation) {
                            v.setVisibility(View.GONE);
                            spv_silk.removeView(v);

                            mTotalSilkAmount += ((SilkHomeInfo.SilkProduceRecord) v.getTag()).amount;
                            tv_total_silk_amount.setText(getString(R.string.silk_amount, mDecimalFormat.format(mTotalSilkAmount)));
                        }
                    })
                    .setDuration(600)
                    .start();
            mSoundPool.play(mSoundID, 0.7f, 0.7f, 0, 0, 1);

            receiveSilkProduceRecord((SilkHomeInfo.SilkProduceRecord) v.getTag());
        });
        return textView;
    }

    private void receiveSilkProduceRecord(SilkHomeInfo.SilkProduceRecord record) {
        compositeDisposable.add(RestAPI.getInstance().oSellService()
                .receiveSilkProduceRecord(mUserInfoSp.getString("user_id", ""),
                        mUserInfoSp.getString("user_key", ""), record.uuid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(stringResponseData -> {
                }, throwable -> {
                }));
    }


    private void animateTheInProduction() {
        ObjectAnimator animator = ObjectAnimator.ofFloat(tv_in_production, View.TRANSLATION_Y, 0, -40);
        animator.setDuration(3000).setRepeatMode(ValueAnimator.REVERSE);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.setStartDelay(1000);
        animator.start();
        tv_in_production.setTag(animator);
    }

    private void animateTheSilk() {
        spv_silk.postDelayed(() -> {
            for (int i = 0; i < spv_silk.getChildCount(); i++) {
                View view = spv_silk.getChildAt(i);
                if (((SilkProduceView.LayoutParams) view.getLayoutParams()).layoutMode == SilkProduceView.LayoutParams.RANDOM) {
                    ((AnimatorSet) view.getTag(R.id.spv_silk)).start();
                }
            }
        }, 1000);
    }
}
